package jzqb.dao.impl;

import cnki.tpi.base.DataContext;
import cnki.tpi.base.DataSourceManager;
import cnki.tpi.kbatis.sqlsession.SqlSession;
import cnki.tpi.kbatis.utils.DataSourceUtil;
import jzqb.bo.AdminPermissionGroupBo;
import jzqb.bo.AdminPermissionGroup_getuserBo;
import jzqb.bo.QBZSBo;
import jzqb.bo.StandardBo;
import jzqb.common.Result;
import jzqb.dao.AdminPermissionDao;
import jzqb.po.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.*;


@Repository
public class AdminPermissionDaoImpl implements AdminPermissionDao {

    @Autowired
    private DataSourceManager kbaseDs;

    @Autowired
    private DataContext dataContext;

    @Override
    public List<AdminPermissionGroupPo> cutList(AdminPermissionGroupBo adminPermissionGroupBo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminPermissionDao.getPermissionGroupList";
        List<AdminPermissionGroupPo> cutList = sqlSession.selectList(statementId, adminPermissionGroupBo,false);


        //查每个权限组的数据权限
        for (int i = 0; i < cutList.size(); i++) {
            AdminPermissionGroupPo po = cutList.get(i);
            String id = po.getPermissionGroupID();
            String statementId_ = "jzqb.dao.AdminPermissionDao.getQXByQXZID";
            AdminPermissionPo permisssionPo = sqlSession.selectOne(statementId_, id,false);
            if (permisssionPo != null){
                po.setDataPermission(permisssionPo.getType1());
            }
        }
        return cutList;
    }

    @Override
    public long cutCount(AdminPermissionGroupBo adminPermissionGroupBo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminPermissionDao.getPermissionGroupListCount";
        long num=sqlSession.getCount(statementId,adminPermissionGroupBo);
        return num;
    }

    @Override
    public List<AdminUserPo> cutList_(AdminPermissionGroup_getuserBo adminUserInfoBo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminPermissionDao.getSSSList_";
        List<AdminUserPo> cutList = sqlSession.selectList(statementId, adminUserInfoBo,false);
        return cutList;
    }

    @Override
    public List<AdminUserPo> cutList_switchShow(AdminPermissionGroup_getuserBo adminUserInfoBo) {


        ArrayList<String> idList = new ArrayList<String>();
        for (String id :adminUserInfoBo.getIds().split(";")){
            idList.add("ID=" + id);
        }

        if (("").equals(adminUserInfoBo.getUsernameORid())){
            adminUserInfoBo.setUsernameORid(String.join(" or ",idList));
        }else{
            String temp = String.format("(ID = \"*%s\" or 姓名 = \"*%s\") and (%s)",adminUserInfoBo.getUsernameORid(),adminUserInfoBo.getUsernameORid(),String.join(" or ",idList));
            adminUserInfoBo.setUsernameORid(temp);
        }

        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminPermissionDao.cutList_switchShow";
        List<AdminUserPo> cutList = sqlSession.selectList(statementId, adminUserInfoBo,false);
        return cutList;
    }

    @Override
    public long cutCount_(AdminPermissionGroup_getuserBo adminUserInfoBo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminPermissionDao.getSSSListCount_";
        long num=sqlSession.getCount(statementId,adminUserInfoBo);
        return num;
    }

    @Override
    public long cutCount_switchShow(AdminPermissionGroup_getuserBo adminUserInfoBo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminPermissionDao.getSSSListCount_switchShow";
        long num=sqlSession.getCount(statementId,adminUserInfoBo);
        return num;
    }

    public synchronized Integer getMaxId(){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String getMaxof_statementId = "jzqb.dao.AdminPermissionDao.get_maxID";
        Integer maxId = sqlSession.selectOne(getMaxof_statementId,null, false);
        return maxId;
    };


//    @Override
//    public boolean addeditPermissionGroup(AdminPermissionGroupPo adminPermissionGroupPo) {
//        SqlSession sqlSession = DataSourceUtil.getSqlSession();
////        String statementId = "jzqb.dao.AdminPermissionDao.addeditPermissionGroup";
////        boolean res =sqlSession.executeInsert(statementId,adminPermissionGroupPo);
//        //新建
//        if (adminPermissionGroupPo.getPermissionGroupID().equals("")){
//            String insertPermissionGroup_statementId = "jzqb.dao.AdminPermissionDao.addPermissionGroup";
//            boolean res_1 =sqlSession.executeInsert(insertPermissionGroup_statementId,adminPermissionGroupPo);
//            if (res_1){
//                //获取新添加的权限组的id
//                Integer maxId = getMaxId();
//
//                String insertPermission_statementId = "jzqb.dao.AdminPermissionDao.addPermission";
//                adminPermissionGroupPo.setPermissionGroupID(Integer.toString(maxId));
//                boolean res_2 =sqlSession.executeInsert(insertPermission_statementId,adminPermissionGroupPo);
//            }
//            return true;
//        }else{
//        //编辑
//            String updatePermissionGroup_statementId = "jzqb.dao.AdminPermissionDao.editPermissionGroup";
//            boolean res_1 =sqlSession.executeInsert(updatePermissionGroup_statementId,adminPermissionGroupPo);
//            if (res_1){
//                String updatePermission_statementId = "jzqb.dao.AdminPermissionDao.editPermission";
//                boolean res_2 =sqlSession.executeInsert(updatePermission_statementId,adminPermissionGroupPo);
//                if (res_1 & res_2){
//                    return true;
//                }else{
//                    return false;
//                }
//            }else{
//                return false;
//            }
//        }
//    }



    @Override
    /*
    * 重构后的,新建和编辑权限组
    * */
    public boolean addeditPermissionGroup(AdminPermissionGroupPo adminPermissionGroupPo) {
//        1. 权限组表(YQTQXZB)中新建一个权限组
//        2. 获取刚刚新建的权限组的自增ID
//        3. 数据权限表(YQTSJQXB)中新建若干数据,记录这个权限组包含的数据权限
//        说明:类型:0   整库
//        说明:类型:1   某库某领域
//        说明:类型:1   某库某领域某条数据
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        //新建
        if (adminPermissionGroupPo.getPermissionGroupID().equals("")){
            String insertPermissionGroup_statementId = "jzqb.dao.AdminPermissionDao.addPermissionGroup";
            boolean res_1 =sqlSession.executeInsert(insertPermissionGroup_statementId,adminPermissionGroupPo);
            if (res_1){
                //获取新添加的权限组的id
                Integer maxId = getMaxId();

                AdminDataPermissionPo adminDataPermissionPo = new AdminDataPermissionPo();
                adminDataPermissionPo.setPermissionGroupID(Integer.toString(maxId));
                for (String record:adminPermissionGroupPo.getNewDataPermission().split(";")) {
                    int leng = record.split("-").length;
                    if (leng==1){
                        String dbcode = record;

                        adminDataPermissionPo.setType("0");
                        adminDataPermissionPo.setDbCode(dbcode);
                        adminDataPermissionPo.setField("");
                        adminDataPermissionPo.setPd("");
                    }
                    else if (leng == 2){
                        String dbcode = record.split("-")[0];
                        String field = record.split("-")[1];

                        adminDataPermissionPo.setType("1");
                        adminDataPermissionPo.setDbCode(dbcode);
                        adminDataPermissionPo.setField(field);
                        adminDataPermissionPo.setPd("");
                    }
                    else if (leng ==3){
                        String dbcode = record.split("-")[0];
                        String field = record.split("-")[1];
                        String sysid = record.split("-")[2];

                        adminDataPermissionPo.setType("2");
                        adminDataPermissionPo.setDbCode(dbcode);
                        adminDataPermissionPo.setField(field);
                        adminDataPermissionPo.setPd(sysid);
                    }
                    String insertPermission_statementId = "jzqb.dao.AdminPermissionDao.addPermission_rebuilt";
                    boolean res_2 =sqlSession.executeInsert(insertPermission_statementId,adminDataPermissionPo);
                }

            }
            return true;
        }else{
            //编辑
            // 1 先在JZSJQXZ中,删除该 数据权限组 的所有数据
            //2 重新在JZSJQXZ,插入若干条数据
            //3 更新 权限组名,部门成员,用户成员 的数据

            String updatePermissionGroup_statementId = "jzqb.dao.AdminPermissionDao.deleteDataProms";

            AdminDataPermissionPo adminDataPermissionPo = new AdminDataPermissionPo();
            adminDataPermissionPo.setPermissionGroupID(adminPermissionGroupPo.getPermissionGroupID());
            boolean res_1 =sqlSession.executeInsert(updatePermissionGroup_statementId,adminDataPermissionPo);
            for (String record:adminPermissionGroupPo.getNewDataPermission().split(";")) {
                int leng = record.split("-").length;
                if (leng==1){
                    String dbcode = record;

                    adminDataPermissionPo.setType("0");
                    adminDataPermissionPo.setDbCode(dbcode);
                    adminDataPermissionPo.setField("");
                    adminDataPermissionPo.setPd("");
                }
                else if (leng == 2){
                    String dbcode = record.split("-")[0];
                    String field = record.split("-")[1];

                    adminDataPermissionPo.setType("1");
                    adminDataPermissionPo.setDbCode(dbcode);
                    adminDataPermissionPo.setField(field);
                    adminDataPermissionPo.setPd("");
                }
                else if (leng ==3){
                    String dbcode = record.split("-")[0];
                    String field = record.split("-")[1];
                    String sysid = record.split("-")[2];

                    adminDataPermissionPo.setType("2");
                    adminDataPermissionPo.setDbCode(dbcode);
                    adminDataPermissionPo.setField(field);
                    adminDataPermissionPo.setPd(sysid);
                }
                String insertPermission_statementId = "jzqb.dao.AdminPermissionDao.addPermission_rebuilt";
                boolean res_2 =sqlSession.executeInsert(insertPermission_statementId,adminDataPermissionPo);

            }

            String updatePermissionGroup_statementId_2 = "jzqb.dao.AdminPermissionDao.editPermissionGroup";
            boolean res_2 =sqlSession.executeInsert(updatePermissionGroup_statementId_2,adminPermissionGroupPo);

            return true;
        }
    }

    @Override
    public boolean deletePermissionGroup(AdminPermissionGroupPo adminPermissionGroupPo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminPermissionDao.deletePermissionGroup";
        boolean res =sqlSession.executeInsert(statementId,adminPermissionGroupPo);
        return res;
    }

    @Override
    public boolean permissionCheck(String ID,String[] permissions){
        //1 获取此人的id(已知)和部门(可能有多个)
        //2 通过id和部门获取此人的权限组集合
        //3 获取权限组集合具有的所有权限
        //4 判断本次请求所需权限是否 是 步骤3 的子集


        if (permissions.length==1 &&  "" .equals(permissions[0])){
            return true;
        }

        //1 获取此人的id(已知)和部门(可能有多个)
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId_1 = "jzqb.dao.AdminUserInfoDao.findUserById";
        AdminUserPo userPo = sqlSession.selectOne(statementId_1, ID, false);

        ArrayList<String> deps = new ArrayList<String>();
        if (!userPo.getDepartmentid().equals("")){
            for (String depId:userPo.getDepartmentid().split(";")) {
                deps.add(depId);
            }
        }


        System.err.println("认证1:此人的部门有:"+deps);
        //2 通过id和部门获取此人的权限组集合
        String statementId_2 = "jzqb.dao.AdminPermissionDao.getQXZByID_deps";
        ArrayList<String> conditionList = new ArrayList<String>();
        conditionList.add("用户成员 = " + "'" + ID + "'");
//        if (deps.size()!=0){
            for (String depid:deps
            ) {
                conditionList.add("部门成员 =" + "'" + depid + "'");
            }
//        }

        String condition = String.join(" or ",conditionList);

        List<AdminPermissionGroupPo> adminPermissionGroupPoList =  sqlSession.selectList(statementId_2, condition,false);

        //
        ArrayList<String> allPermissionGroupIdList = new ArrayList<String>();
        for (AdminPermissionGroupPo adminPermissionGroupPo:adminPermissionGroupPoList
             ) {
            allPermissionGroupIdList.add(adminPermissionGroupPo.getPermissionGroupID());
        }
        System.err.println("认证2:此人的所有 权限组 有:"+allPermissionGroupIdList);
        //3 获取权限组集合具有的所有权限
        ArrayList<String> conditionList_2 = new ArrayList<String>();
        for (String permissionGroupId:allPermissionGroupIdList
             ) {
            conditionList_2.add("权限组ID=" + permissionGroupId);
        }
        String condition_2 = String.join(" or ",conditionList_2);
        String statementId_3 = "jzqb.dao.AdminPermissionDao.getQXByQXZs";
        List<AdminPermissionPo> adminPermissionPoList =  sqlSession.selectList(statementId_3, condition_2,false);
        System.err.println("认证3:此人的所有 权限 有:"+adminPermissionPoList);
        //4 判断本次请求所需权限是否 是 步骤3 的子集
        System.err.println("认证4:此操作需要的 权限 有:");
        for (String item:permissions) {
            System.err.println(item);
        }

        //获取个人的所有权限(含重复数据)--list
        List hisAllPermissionList =new ArrayList();
        for (AdminPermissionPo po:adminPermissionPoList) {
            for (String permission:po.getIncludes().split(";")) {
                hisAllPermissionList.add(permission);
            }
        }
        //定义集合
        Set hisAllPermissionSet = new HashSet();
        //获取个人的所有权限(去重)--set
        hisAllPermissionSet.addAll(hisAllPermissionList);


        //获取当前操作需要的权限(由开发者提供,一般不会重复) list
        List needPermissionList =new ArrayList();
        for (String needPer:permissions) {
            needPermissionList.add(needPer);
        }
        //定义集合
        Set needPermissionSet = new HashSet();
        //获取当前操作需要的权限(去重)--set
        needPermissionSet.addAll(needPermissionList);

        //判断 需要的.. 是否是 所有的.. 子集
        boolean result = hisAllPermissionSet.containsAll(needPermissionSet);
        return result;
//        if (type.equals("f")){
//            return result;
//        }else{
//            //占位用,数据权限验证时间修改
//            return true;
//        }

    }


    @Override
    public Result getPermissionTreeExisted(String permissionGroupID){
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminPermissionDao.getPermissionTreeExisted";

        List<AdminDataPermissionPo> cutList = sqlSession.selectList(statementId, permissionGroupID,false);
        return Result.succ(cutList);
    }


    @Override
    public boolean checkDataPermission(String userid, QBZSBo qbzsBo,String accessType){
        /*
        *    id---------个人权限组--->个人数据权限┐
        *     ↓                                 |
        *  用户对象                             |--->所有数据权限(如果为空-->直接返回false)
        *     ↓                               |
        *    部门------部门权限组-->部门数据权限┘
        *
        *      qbzsBo
        *      ↓    ↓
        *tableName sysID
        *         +
        *         ↓
        *      资源对象
        *     ↓      ↓     ↓
        *tableName sysID field
        *
        *
         * */
        //1 获取此人的id(已知)和部门(可能有多个)
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId_1 = "jzqb.dao.AdminUserInfoDao.findUserById";
        AdminUserPo userPo = sqlSession.selectOne(statementId_1, userid, false);

        ArrayList<String> deps = new ArrayList<String>();
        if (!userPo.getDepartmentid().equals("")){
            for (String depId:userPo.getDepartmentid().split(";")) {
                deps.add(depId);
            }
        }
        //id+部门==>数据权限组
        String statementId_2 = "jzqb.dao.AdminPermissionDao.getSJQXZByID_deps";
        ArrayList<String> conditionList = new ArrayList<String>();
        conditionList.add("用户成员 = " + "'" + userid + "'");
        for (String depid:deps
        ) {
            conditionList.add("部门成员 =" + "'" + depid + "'");
        }
        String condition = String.join(" or ",conditionList);

        List<AdminPermissionGroupPo> adminPermissionGroupPoList =  sqlSession.selectList(statementId_2, condition,false);

        //数据权限组==>数据权限
        ArrayList<String> searchDataPermissionConditionList = new ArrayList<String>();
        for (AdminPermissionGroupPo adminPermissionGroupPo:adminPermissionGroupPoList
        ) {
            searchDataPermissionConditionList.add("权限组ID = " + "'"+adminPermissionGroupPo.getPermissionGroupID()+ "'");
        }
        String searchDataPermissionConditionStr = String.join(" or ",searchDataPermissionConditionList);

        //如果没有任何数据权限,直接返回false
        if (searchDataPermissionConditionList.size()==0){
            return false;
        }

        String getDataPermissionBypermissionGroup_sql = "jzqb.dao.AdminPermissionDao.getDataPermissionBypermissionGroupIDs";
        List<AdminDataPermissionPo> dataPermissions =  sqlSession.selectList(getDataPermissionBypermissionGroup_sql, searchDataPermissionConditionStr,false);

        //获取访问资源的领域
        String getFieldOfResource = "jzqb.dao.QBZSDao.getQBZSInfo";
//        String QBZSconditionStr = String.format("SYS_FLD_SYSID='%s'",qbzsBo.getSysID());
        QBZSPo QBZSpo = sqlSession.selectOne(getFieldOfResource, qbzsBo,false);

        for (AdminDataPermissionPo po:dataPermissions){
            if (
                    ("0".equals(po.getType()) && po.getDbCode().equals(QBZSpo.getTableName()))||
                    ("1".equals(po.getType()) && po.getDbCode().equals(QBZSpo.getTableName()) && po.getField().equals(QBZSpo.getArea()))||
                    ("2".equals(po.getType()) && po.getDbCode().equals(QBZSpo.getTableName()) && po.getField().equals(QBZSpo.getArea()) && accessType.equals(po.getPd()))
            ){
                    return true;
            }
        }
        return false;
    }


    @Override
    public boolean addBrowseDownLoadLog(String operateType, String userId, StandardBo bo) {
        SqlSession sqlSession = DataSourceUtil.getSqlSession();
        String statementId = "jzqb.dao.AdminPermissionDao.addBrowseDownLoadLog";
        AdminViewDownLogPo po = new AdminViewDownLogPo();
        po.setUserID(userId);
        po.setSource(bo.getSource());
        po.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        if ("p".equals(operateType)){
            po.setAccessType("浏览");
        }
        else if ("d".equals(operateType)){
            po.setAccessType("下载");
        }
        else{
            po.setAccessType("未知方式");
        }
        po.setFileName(bo.getFileDistinct());

        boolean res = sqlSession.executeInsert(statementId,po);
        return res;
    }

}
